//index.js
//获取应用实例

var app = getApp()
var time_go = '';
var envelope_num = 0;
var token = wx.getStorageSync('token_key');
Page({
  data: {
    moduleSort: '',
    envelope_list: '',
    imgurl: app.urlimg,
    envelope: false,
    // 文字轮播
    text_banner: [
      { text: '一二三四五六七八九十一二三四五六七八九十' },
      { text: '222222222222222222222222222222222222222222222222222' },
      { text: '33333333333333333' },
    ],
    /* 拼团好货 */
    inlet: [
      { img: 'https://lteimg1.camel.com.cn/upload/wx/lottery06.gif', url: '/pages/group/lottery/lottery', },//抽奖团
      { img: 'https://lteimg1.camel.com.cn/upload/wx/dijiatuangou06.jpg', url: '/pages/group/group', },//拼团
      { img: 'https://lteimg1.camel.com.cn/upload/wx/yifeng06.jpg', url: '/pages/group/lottery/lottery', },//抽奖团
    ],
    userInfo: {},
    // 首页面的广告模板
    picture: [],
    commend_goods: {},
    data: {},
    defaultpages: 1,
    loadHidden: true,
    loadText: "加载中...",
    toastHidden: true,
    msg: '已经到最底了',
    isScrollTop: true,
    images: {},
    categoods: {},


    load_status: true,
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  // 首页面的广告模板
  advertising_click: function (e) {
    var that = this;
    console.log(e.currentTarget.dataset.url);
    var url = e.currentTarget.dataset.url;
    // 保存用户点击模板的次数
    for (var i in that.data.moduleSort) {
      if (i == e.currentTarget.dataset.template_id) {
        template_user_click(that.data.moduleSort[i].id);
      }
    }
    //页面跳转
    wx.navigateTo({
      url: url,
    })
  },
  //限时抢购列表页跳转
  toast: function (e) {
    var that = this;
    // 保存用户点击模板的次数
    for (var i in that.data.moduleSort) {
      if (i == e.currentTarget.dataset.template_id) {
        template_user_click(that.data.moduleSort[i].id);
      }
    }
    //页面跳转
    wx.navigateTo({
      url: '/pages/timegoods/index'
    })
  },

  //专题页界面入口
  thematic_click: function () {
    wx.navigateTo({
      url: "/pages/index/detail/thematic/index",
    })
  },
  //打包一口价界面入口
  price_click: function () {
    wx.navigateTo({
      url: "/pages/index/detail/price/index",
    })
  },
  // 抢红包入口
  packet_click: function () {
    wx.navigateTo({
      url: "/pages/index/detail/packet/index",
    })
  },
  // 入口界面
  inlet_click: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var url = e.currentTarget.dataset.url;
    // 保存用户点击模板的次数
    for (var i in that.data.moduleSort) {
      if (i == e.currentTarget.dataset.template_id) {
        template_user_click(that.data.moduleSort[i].id);
      }
    }
    //页面跳转
    wx.navigateTo({
      url: url,
    })
  },
  //
  scroll: function (e) {
    var that = this;
    if (e.detail.scrollTop > 500) {
      that.setData({ isScrollTop: false, });
    } else {
      that.setData({ isScrollTop: true, });
    }
  },
  // 关闭弹出红包函数
  envelope_click: function () {
    var that = this;
    var envelope_list = that.data.envelope_list;
    console.log(envelope_list);
    var envelope_list_one = that.data.envelope_list_one;
    var envelope = true;

    for (var i = 0; i < envelope_list.length; i++) {
      if (envelope_list[i].id == envelope_list_one.id) {
        envelope_list[i].state = false;
        ++i;
        if (envelope_list[i] != undefined && envelope_list[i].state) {
          envelope_list_one = envelope_list[i];
          console.log(envelope_list_one);
        }
      }
    }
    ++envelope_num;
    console.log(envelope_num);
    console.log(envelope_list.length);
    if (envelope_num == envelope_list.length || envelope_num > envelope_list.length) {
      envelope = false;
    }
    console.log(envelope_list);
    that.setData({
      envelope: envelope,
      envelope_list: envelope_list,
      envelope_list_one: envelope_list_one
    })
  },
  onLoad: function (o) {
    wx.showLoading({ title: '加载中···' })
    this.setData({ load_status: false, })
    envelope_num = 0;
    //判断用户进入商品详情页的次数（用于控制客服提示的次数）
    wx.setStorage({
      key: "entrance",
      data: "0",
    })

    wx.login({
      success: function (res) {
        console.log(res)
      }
    })

    console.log(o)
    var that = this;
    // console.log(wx.getStorageSync('token_key'))
    wx.getSystemInfo({
      success: function (res) {
        console.info(res.windowHeight);
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });



    // app.getUserInfo(function (token_key) {
    //that.getHomeData(token_key);
    //wx.getStorageSync('token_key')
    var tg = typeof (o.tg) == 'undefined' ? 0 : o.tg
    wx.request({
      url: app.url + 'api_goods/index',
      data: {
        tg: tg,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        wx.hideLoading();
        console.log(json.data.result.moduleSort)
        console.log(json)
        wx.hideLoading();
        that.setData({
          data: json.data.result,
          picture: json.data.result.indexTopic,
          moduleSort: json.data.result.moduleSort,
        })
      }
    })
    wx.request({
      url: app.url + 'api_goods/categoryListTopV1',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        console.log(json)
        that.setData({
          categoryList: json.data.result,
          //	commend_goods: json.data.result,
        })

      }
    })

    //弹出红包
    wx.request({
      url: app.url + 'api_advertise/advertise_pop',
      data: {},
      header: {
        'content-type': 'application/json',
        'token': token,
      },
      success: function (json) {
        var envelope = false;
        var envelope_list_one = json.data.result[0];
        if (json.data.done == true) {
          envelope = true;
        }
        that.setData({
          envelope: envelope,//弹出红包（用户每天第一次进去）
          envelope_list: json.data.result,
          envelope_list_one: (envelope_list_one != undefined ? envelope_list_one :''),
        })
      }
    })

    //专题页倒计时
    wx.request({
      url: app.url + '?controller=api_goods&action=homeTime',
      data: {},
      header: {
        'content-type': 'application/json',
        'token': token
      }, success: function (res) {
        if (res.data.done) {
          console.log(res)
          that.setData({
            computations_time: res.data.result,
            current_time: Date.parse(new Date()) / 1000,
          })
          console.log(that.data.computations_time);
          var time_box = '';
          if (that.data.computations_time) {
            if (parseInt(that.data.computations_time[0].start_time) > parseInt(that.data.current_time)) {
              time_box = parseInt(that.data.computations_time[0].start_time) - parseInt(that.data.current_time);
            } else {
              time_box = parseInt(that.data.computations_time[0].end_time) - parseInt(that.data.current_time);
            }
          }
          // console.log(time_box);
          if (time_box > 0) {
            time_computations(time_box, that);
          } else {
            clearInterval(time_go);
            that.setData({
              computations_time: false,
            })
          }
        } else {
          that.setData({
            // envelope: true,//弹出红包（用户每天第一次进去）
            computations_time: false,
          })
          clearInterval(time_go);
        }

      }
    })
    //app.aldstat.debug("这是条调试信息"); 
  },
  new_goods_link: function (o) {
    var that = this;
    // 保存用户点击模板的次数
    for (var i in that.data.moduleSort) {
      if (i == e.currentTarget.dataset.template_id) {
        template_user_click(that.data.moduleSort[i].id);
      }
    }
    //页面跳转
    wx.navigateTo({
      url: '/pages/new/new',
    })
  },
  //  搜索按钮被单击
  searchTAP: function (e) {
    this.search = true;
    wx.navigateTo({
      url: '/pages/search/index',
    })
  },
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images: image
    })
  },
  image_top_time: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 750,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 750 / ratio;    //计算的高度值
    var image = {};
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images_top_time: image
    })
  },
  ad_link: function (e) {
    if (e.target.id) {
      wx.navigateTo({
        url: '/pages/index/detail/index?id=' + e.target.id,
      })
    }
  },
  swiperItem: function (e) {
    var that = this;
    var fid = e.currentTarget.id
    if (e.currentTarget.dataset.url !== '') {
      // 保存用户点击模板的次数
      for (var i in that.data.moduleSort) {
        if (i == e.currentTarget.dataset.template_id) {
          template_user_click(that.data.moduleSort[i].id);
        }
      }
      // 页面跳转
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      })
    }
  },
  // 响应分类单击
  categoryTAP: function (e) {
    var that = this;
    var fid = e.currentTarget.id
    var name = e.currentTarget.dataset.name;
    // 保存用户点击模板的次数
    for (var i in that.data.moduleSort) {
      if (i == e.currentTarget.dataset.template_id) {
        template_user_click(that.data.moduleSort[i].id);
      }
    }
    //页面跳转
    wx.navigateTo({
      url: '/pages/goods/index?category_id=' + fid + '&name=' + name,
    })
  },
  //  响应推荐商品单击
  coomodityTAP: function (e) {
    var that = this;
    var fid = e.currentTarget.id;
    // 保存用户点击模板的次数
    for (var i in that.data.moduleSort) {
      if (i == e.currentTarget.dataset.template_id) {
        template_user_click(that.data.moduleSort[i].id);
      }
    }
    //页面跳转
    wx.navigateTo({
      url: '/pages/index/detail/index?id=' + fid
    })
  },
  getHomeData: function (token_key) {
    var that = this
    wx.request({
      url: app.url + 'api_goods/index',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'token': token_key
      }, success: function (json) {
        that.setData({
          data: json.data.result
        })
      }
    })
    wx.request({
      url: app.url + 'api_goods/categoryListTopV1',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'token': token
      }, success: function (json) {
        // console.log(json)
        that.setData({
          categoryList: json.data.result
        })
        //that.setData({ commend_goods: json.data.result })
      }
    })
  },

  onReachBottom: function () {
    var page = this;
    var that = this;
    that.setData({ loadHidden: false })
    //判断是全部还是默认
    var forumPage = page.data.defaultpages
    wx.request({
      url: app.url + 'api_goods/categoryListTopV1',
      data: {
        page: forumPage,
      },
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: function (res) {
        if (res.data.done == true) {
          console.log(res.data.result);
          var p = that.data.defaultpages
          page.setData({
            defaultpages: ++forumPage,
            commend_goods: res.data.result
          })
        } else {
          page.setData({ toastHidden: false, loadText: '--已经到最底了--' })
        }
      }, complete: function () {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    })

  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh;
  },


  l_home: function (e) {
    wx.reLaunch({
      url: '/pages/tabBar/index/index',
    })
  },
  // 
  l_cate: function (e) {
    wx.reLaunch({
      url: '/pages/category/index'
    })
  },

  l_cart: function (e) {
    wx.reLaunch({
      url: '/pages/shop/index'
    })
  },
  l_account: function (e) {
    wx.reLaunch({
      url: '/pages/tabBar/account/index'
    })
  },

  toastChange: function () {
    this.setData({ toastHidden: true })
  },
  onShareAppMessage: function () {
    return {
      title: app.shopName,
      path: 'pages/index/index'
    }
    wx.setNavigationBarTitle({
      title: app.shopName,
    })
  },
  scrollChange: function (e) {
    var that = this;
    that.setData({
      defaultpages: ++that.data.defaultpages, loadHidden: true,
    });
    var forumPage = that.data.defaultpages
    console.log(forumPage + '页')
		/*
			 that.pageData(forumPage)*/
    var newList = that.pageData(forumPage)
    that.setData({
      commend_goods: newList
    })

  },
  // 监听返回顶部
  scrollTop: function (e) {
    console.log(666)
    this.setData({
      toTop: 0,
      isScrollTop: true,
    });

  },
	/**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {
    var that = this;
    if (that.data.load_status) {
      that.onLoad();
    }
    time_go = setInterval(function () {
      if (that.data.computations_time) {
        var start_time = that.data.computations_time[0].start_time;
        var end_time = that.data.computations_time[0].end_time;
        var time_box = '';
        if (parseInt(start_time) > Date.parse(new Date()) / 1000) {
          time_box = parseInt(start_time) - Date.parse(new Date()) / 1000;
        } else {
          time_box = parseInt(end_time) - Date.parse(new Date()) / 1000;
        }
        if (time_box > 0) {
          time_computations(time_box, that);

        } else {
          that.setData({
            computations_time: false,
          })
          clearInterval(time_go);
        }
      } else {
        clearInterval(time_go);
      }
    }, 1000);


  },
  onHide: function () {
    clearInterval(time_go);
  },
  onUnload: function () {
    clearInterval(time_go);
  },
  autoFormId: function (e) {
    wx.request({
      url: app.url + "api_team/collectFormId",
      data: {
        formId: e.detail.formId
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (result) { }
    });
  }
})

function time_computations(Times, that) {
  // console.log(Times);

  var day = Math.floor(Times / (60 * 60 * 24));//计算剩余的天数

  var hours = parseInt(Times / 60 / 60 % 24, 10); //计算剩余的小时
  if (('' + hours).length == 1) {
    hours = '0' + hours;
  }
  var minutes = parseInt(Times / 60 % 60, 10);//计算剩余的分钟
  if (('' + minutes).length == 1) {
    minutes = '0' + minutes;
  }
  var seconds = parseInt(Times % 60, 10);//计算剩余的秒数
  if (('' + seconds).length == 1) {
    seconds = '0' + seconds;
  }
  //倒计时判断
  var new_time = [];
  new_time[0] = day;//排列时间
  new_time[1] = hours;//排列时间
  new_time[2] = minutes;//排列时间
  new_time[3] = seconds;//排列时间
  that.setData({
    new_time: new_time,
    current_time: Date.parse(new Date()) / 1000,
  })
}



// 保存用户点击模板的次数
function template_user_click(e) {
  console.log(e);
  wx.request({
    url: app.url + 'api_traffic/index_module_statistics',
    data: {
      id: e
    },
    header: {
      'content-type': 'application/json',
      'token': wx.getStorageSync('token_key'),
    },
    success: function (res) {
      console.log('保存用户点击模板的次数');
      console.log(res.data.result);
    },
  })
};